import { reqGetChannels, reqGetMyChannels } from '../../api/channels'

const state = {
  channelList: [],
  allChannels: []
}
const mutations = {
  // 存储我的频道
  setChannels (state, channels) {
    state.channelList = channels
  },
  // 存储所有频道
  setAllChannels (state, channels) {
    state.allChannels = channels
  },
  // 新增我的频道
  addMyChannels (state, channel) {
    state.channelList.push(channel)
  },
  // 删除我的频道
  delMyChannels (state, channel) {
    state.channelList.splice(state.channelList.findIndex(item => item === channel), 1)
  }
}
const actions = {
  // 获取我的频道
  async GetMyChannels (context) {
    const res = await reqGetMyChannels()
    context.commit('setChannels', res.data.channels)
  },
  // 获取所有频道
  async GetAllChannels (context) {
    const res = await reqGetChannels()
    context.commit('setAllChannels', res.data.channels)
  }
}
const getters = {
  // 筛选可选频道
  optionalChannels: (state) => {
    const results = state.allChannels.filter(channel => {
      const index = state.channelList.findIndex(item => item.id === channel.id)
      return index === -1
    })
    return results
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
